﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.ComponentModel;
using SMS.Entities.BaseClasses;
using SMS.Entities.Admin;
using SMS.Model;
using System.IO.IsolatedStorage;
using SMS.Common.Silverlight;
using System.Collections.Generic;
using System.Runtime.Serialization;
using System.IO;
using System.Windows.Browser;
using System.Windows.Media.Imaging;

namespace SMS.ViewModel
{
    public class ViewModel_MainPage : BaseNotify
    {
        Grid grid;
        AuthenticationModel authenticate;
        public ViewModel_MainPage(SMS.Entities.Admin.ApplicationUser applicationUser, Grid _grid)
        {
            InitializeCommponent();
            App.OnSessionExpired += new Action<bool>(App_OnSessionExpired);
            CurrentUser = applicationUser;
            grid = _grid;
            InitializeModel();
            if (CurrentUser != null)
            {
                App.LoggedinUserName = CurrentUser.UserName;
                App.LoggedInTime = CurrentUser.LastLogin.ToShortTimeString();
                if (CurrentUser.Role == 2)
                {
                    IsVisisbleAddNewButton = Visibility.Visible;
                    IsVisibleAdminHyperLink = Visibility.Visible;
                }
                GetBranchDetail(CurrentUser);
                LoadImage(CurrentUser.PicturePath);
            }
            MainPageContext = this;
            FrameControl = ControlFinder.GetChildren<Frame>(grid)[0];
            LoggedInUserDetail = CurrentUser.FirstName + " " + CurrentUser.LastName;
        }

        void App_OnSessionExpired(bool obj)
        {
            Logout_Click(null);
        }

        private void GetBranchDetail(ApplicationUser CurrentUser)
        {
            authenticate.GetBranchDetail(CurrentUser.Branch.Branch_ID);
        }

        private void InitializeModel()
        {
            authenticate = new AuthenticationModel();
            authenticate.AuthenticationCompleted += new Action<Entities.Admin.ApplicationUser>(authenticate_AuthenticationCompleted);
            authenticate.GetBranchDetailCompleted += new Action<Entities.Master.Branch>(authenticate_GetBranchDetailCompleted);
        }

        void authenticate_GetBranchDetailCompleted(Entities.Master.Branch obj)
        {
            if (obj != null)
            {                
                WelcomeMsg = "Branch:  " + obj.BranchName; 
            }
        }

        private void InitializeCommponent()
        {
            LogoutCommand = new DelegateCommand(Logout_Click, null);
            ResetPasswordCommand = new DelegateCommand(ResetPasswordClickCommand, null);
            ProfileSettingsCommand = new DelegateCommand(ProfileSettings);
        }


        private void ResetPasswordClickCommand(object param)
        {
            var show = new Views.ResetPasswordChildWindow();
            show.Show();
        }

        private void Logout_Click(object param)
        {
            authenticate.AuthenticateUser(CurrentUser.UserName, string.Empty, false);            
        }

        private void ProfileSettings(object param)
        {
 
        }

        void authenticate_AuthenticationCompleted(Entities.Admin.ApplicationUser obj)
        {
            using (IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForSite())
            {
                if (store.FileExists("Login.dat"))
                    store.DeleteFile("Login.dat");
                Views.Login.LoginPage objLoginPage = new Views.Login.LoginPage();
                grid.Children.Clear();
                grid.Children.Add(objLoginPage);
                grid.Background = new SolidColorBrush(Colors.White);
                
            }
        }

        private void LoadImage(string fileName)
        {
            WebClient downloader = new WebClient();
            downloader.OpenReadCompleted += new OpenReadCompletedEventHandler(downloader_OpenReadCompleted);
            //downloader.DownloadProgressChanged += new DownloadProgressChangedEventHandler(downloader_DownloadProgressChanged);

            string host = Application.Current.Host.Source.AbsoluteUri;
            host = host.Remove(host.IndexOf("/ClientBin"));

            fileName = host + "/Images/" + fileName;
            downloader.OpenReadAsync(new Uri(fileName, UriKind.Absolute));
        }

        void downloader_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
        {
            if (e.Error == null && e.Result != null)
            {
                BitmapImage loadedImage = new BitmapImage();
                loadedImage.SetSource(e.Result);
                ImageUrl = loadedImage;
            }
            else
            {
                LoadImage("bipin.jpg");
            }
        }
	 


        #region Properties

        private BitmapImage _ImageUrl;

        public BitmapImage ImageUrl
        {
            get { return _ImageUrl; }
            set { _ImageUrl = value; OnPropertyChanged("ImageUrl"); }
        }
        

        private ApplicationUser _currentUser;

        public ApplicationUser CurrentUser
        {
            get { return _currentUser; }
            set
            {
                _currentUser = value;
                if (value != null)
                    //WelcomeMsg = "Logged in as: " + CurrentUser.UserName.ToUpper() + " on " + CurrentUser.LastLogin;
                OnPropertyChanged("CurrentUser");
            }
        }

        private string _welcomeMsg;

        public string WelcomeMsg
        {
            get { return _welcomeMsg; }
            set { _welcomeMsg = value; OnPropertyChanged("WelcomeMsg"); }
        }

        private string _LoggedInUserDetail;

        public string LoggedInUserDetail
        {
            get { return _LoggedInUserDetail; }
            set { _LoggedInUserDetail = value; OnPropertyChanged("LoggedInUserDetail"); }
        }
        

        public static ViewModel_MainPage MainPageContext { get; set; }

        private Frame _frameControl;
        
        public Frame FrameControl
        {
            get { return _frameControl; }
            set
            {
                _frameControl = value;
                OnPropertyChanged("FrameControl");
            }
        }

        private Visibility _isVisisbleAddNewButton = Visibility.Collapsed;

        public Visibility IsVisisbleAddNewButton
        {
            get { return _isVisisbleAddNewButton; }
            set { _isVisisbleAddNewButton = value; OnPropertyChanged("IsVisisbleAddNewButton"); }
        }

        private Visibility _isVisibleAdminHyperLink = Visibility.Collapsed;

        public Visibility IsVisibleAdminHyperLink
        {
            get { return _isVisibleAdminHyperLink; }
            set { _isVisibleAdminHyperLink = value; OnPropertyChanged("IsVisibleAdminHyperLink"); }
        }

        private SMS.Entities.Master.Branch _BranchObject;

        public SMS.Entities.Master.Branch BranchObject
        {
            get { return _BranchObject; }
            set { _BranchObject = value; OnPropertyChanged("BranchObject"); }
        }
        

        public ICommand LogoutCommand { get; private set; }
        public ICommand ResetPasswordCommand { get; private set; }
        public ICommand ProfileSettingsCommand { get; set; }

        #endregion
    }
}
